package com.pengbos;

import java.io.IOException;
import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class MailServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(MailServlet.class
			.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        
        String name = req.getParameter("name");
        String email =req.getParameter("email");
        String subject =req.getParameter("subject");
        String message = req.getParameter("message");
  
        
		try {
			
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(email,
					name));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
					"pengbos.com@gmail.com", "Pengbos.com"));
			msg.setSubject(subject);
			msg.setText(message);
			Transport.send(msg);

			log.info("Mail success - from :" + email);

			resp.setStatus(200);
			resp.getWriter().write("sent");
		} catch (IOException e) {
			log.info(e.getMessage());
			resp.setStatus(505);
			resp.getWriter().println("Payment Failed w/ IOException");
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			log.info(e.getMessage());
			resp.setStatus(505);
			resp.getWriter().println("mail failed");
		}finally{
			resp.getWriter().flush();
			resp.getWriter().close();
		}
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		doGet(req,resp);
	}
}
